package com.zzw.controller;

import cn.hutool.core.codec.Base64Decoder;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.zzw.dao.TuKuDao;
import com.zzw.model.TuKu;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/imgServer-api")
public class TuKuController {
    @Value("${web.uploadPath}")
    private String baseUploadPath;
    @Resource
    private TuKuDao tuKuDao;
    private final String PATH = "http://localhost:8083/images/";

    @PostMapping("/upload")
    public Integer uploadImg(@RequestBody TuKu tuKu) {
        String base64 = tuKu.getBase64();
        String[] dataArray = StrUtil.splitToArray(base64, "base64,");
        byte[] bytes = Base64Decoder.decode(dataArray[1]);
        String name = IdUtil.simpleUUID() + "_" + tuKu.getName();
        FileUtil.writeBytes(bytes, baseUploadPath + name);
        tuKu.setName(name);
        tuKu.setImg(PATH + name);
        tuKuDao.insert(tuKu);
        return 1;
    }

    @GetMapping("/select")
    public List<TuKu> select() {
        return tuKuDao.select();
    }
}
